package com.mbc.hr.manager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.persistence.EntityManager;

import com.mbc.common.CommonSingleton;
import com.mbc.common.dao.DBManagerFactory;
import com.mbc.common.entities.Notification;
import com.mbc.common.entities.SystemProperty;
import com.mbc.common.entities.User;
import com.mbc.common.utils.EmailUtil;
import com.mbc.hr.entities.CalendarEvent;
import com.mbc.hr.entities.CalendarEventReminder;

public class ReminderMgr{
	
	public static HashMap<String, Timer> timerMap = new HashMap<String, Timer>();
	public static EntityManager em;
	
	private static Calendar calendar = Calendar.getInstance();
	private static Date currentDate = new Date();
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm"); 
	
	static{
		calendar.setTime(currentDate);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
	}
	
	public static long increaseMinute(int minute){
		long l_dateTime = Long.parseLong(dateFormat.format(calendar.getTime()));
		calendar.add(Calendar.MINUTE, minute);
		return l_dateTime;
	}
	
	
	public static void startEventReminderThread(){
		Timer l_timer = new Timer();
		try {
			em = DBManagerFactory.getEntityManager("default");
			SystemProperty l_userProp = em.find(SystemProperty.class, "mail_user");
			SystemProperty l_pwdProp = em.find(SystemProperty.class, "mail_password");
			em.close();
			final String l_emailUser = (l_userProp == null ? "" : l_userProp.getValue());
			final String l_emailPassword = (l_pwdProp == null ? "" : l_pwdProp.getValue());
			
			TimerTask l_task = new TimerTask() {
				
				@Override
				public void run() {
					try {
						em = DBManagerFactory.getEntityManager("default");
						List<CalendarEventReminder> l_reminders = em.createNamedQuery("CalendarEventReminder.findAllByReminderDateTime", CalendarEventReminder.class)
								.setParameter("dateTime", ReminderMgr.increaseMinute(1))
								.setHint("javax.persistence.cache.retrieveMode", "BYPASS")
								.getResultList();
						for (CalendarEventReminder l_reminder : l_reminders) {
							CalendarEvent l_event = em.find(CalendarEvent.class, l_reminder.getEventID());
							if(l_reminder.getReminderType() == 1){ // email
								User l_user = em.find(User.class, l_event.getCreatedBy());
								if(!l_user.getEmail().equals("") && !l_emailUser.equals("") && !l_emailPassword.equals("")){
									String l_fileName = CommonSingleton.ABSOLUTE_PATH + "data\\email_templates\\event_reminder.html";
									SimpleDateFormat l_dateTimeFormat = new SimpleDateFormat("hh:mm a d MMM yyyy");
									HashMap<String, String> l_parameters = new HashMap<String, String>();
									l_parameters.put("{name}", l_user.getUserName());
									l_parameters.put("{event}", l_event.getEventName());
									l_parameters.put("{datetime}", l_dateTimeFormat.format(l_event.getStartDateTime()));
									EmailUtil.sendWithHTMLTemplate(l_user.getEmail(), "Reminder for the event[" + l_event.getEventName() + "]", l_emailUser, l_emailPassword, l_fileName, l_parameters);
								}
							}else{
								SimpleDateFormat l_timeFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
								
								Notification l_noti = new Notification();
								l_noti.setData(l_event.getEventName() + "::" + l_timeFormat.format(l_event.getStartDateTime()));
								l_noti.setNotified(false);
								l_noti.setType((byte)1);
								l_noti.setUserId(l_event.getCreatedBy());
								
								em.getTransaction().begin();
								em.persist(l_noti);
								em.getTransaction().commit();
							}
							em.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			
			l_timer.scheduleAtFixedRate(l_task, 1, 60000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
